#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基本面分析系统 - 第四步执行模块
对股票进行深度基本面分析，评估投资价值
"""

import sys
import os
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from real_data_fetcher import RealDataFetcher

class FundamentalAnalysisSystem:
    """基本面分析系统"""
    
    def __init__(self):
        self.data_fetcher = RealDataFetcher()
        
        # 行业平均估值参考
        self.industry_benchmarks = {
            '银行': {'avg_pe': 6.5, 'avg_pb': 0.8, 'avg_roe': 12.0, 'avg_dividend_yield': 4.5},
            '地产': {'avg_pe': 8.0, 'avg_pb': 1.2, 'avg_roe': 8.0, 'avg_dividend_yield': 3.5},
            '科技': {'avg_pe': 25.0, 'avg_pb': 3.5, 'avg_roe': 15.0, 'avg_dividend_yield': 1.5},
            '消费': {'avg_pe': 18.0, 'avg_pb': 2.5, 'avg_roe': 18.0, 'avg_dividend_yield': 2.8},
            '制造': {'avg_pe': 15.0, 'avg_pb': 2.0, 'avg_roe': 12.0, 'avg_dividend_yield': 3.0},
            '化工': {'avg_pe': 12.0, 'avg_pb': 1.8, 'avg_roe': 10.0, 'avg_dividend_yield': 3.2},
            '电力': {'avg_pe': 11.0, 'avg_pb': 1.1, 'avg_roe': 9.0, 'avg_dividend_yield': 4.0},
            '汽车': {'avg_pe': 20.0, 'avg_pb': 2.2, 'avg_roe': 8.0, 'avg_dividend_yield': 2.0},
        }
        
    def print_header(self, title):
        """打印标题"""
        print(f"\n{'='*80}")
        print(f"💰 {title}")
        print(f"{'='*80}")
        
    def load_technical_results(self, filename="technical_analysis_results.csv"):
        """加载技术分析结果"""
        try:
            df = pd.read_csv(filename)
            return df.to_dict('records')
        except Exception as e:
            print(f"加载技术分析结果失败: {e}")
            return []
            
    def identify_industry(self, stock_code, stock_name):
        """识别股票所属行业"""
        # 基于股票代码和名称的简单行业分类
        if '银行' in stock_name:
            return '银行'
        elif any(word in stock_name for word in ['万科', '地产', '房']):
            return '地产'
        elif any(word in stock_name for word in ['科技', '讯飞', '海康', '电路']):
            return '科技'
        elif any(word in stock_name for word in ['五粮液', '洋河']):
            return '消费'
        elif any(word in stock_name for word in ['万华', '化学']):
            return '化工'
        elif any(word in stock_name for word in ['电力']):
            return '电力'
        elif any(word in stock_name for word in ['比亚迪', '汽车']):
            return '汽车'
        elif any(word in stock_name for word in ['京东方', '制造']):
            return '制造'
        else:
            return '制造'  # 默认分类
            
    def calculate_financial_metrics(self, stock_info):
        """计算财务指标"""
        try:
            # 从股票信息中获取基本指标
            pe_ratio = stock_info.get('pe_ratio', 15)
            market_cap = stock_info.get('market_cap', 100)
            current_price = stock_info.get('current_price', 10)
            
            # 模拟计算其他财务指标
            # 在实际应用中，这些数据应该从财务报表API获取
            pb_ratio = np.random.uniform(0.8, 3.5)  # 市净率
            roe = np.random.uniform(5, 20)          # 净资产收益率
            roa = roe * np.random.uniform(0.3, 0.7) # 总资产收益率
            
            # 毛利率和净利率
            gross_margin = np.random.uniform(15, 45)
            net_margin = np.random.uniform(3, 25)
            
            # 财务杠杆
            debt_ratio = np.random.uniform(0.2, 0.7)
            current_ratio = np.random.uniform(1.0, 3.0)
            
            # 成长性指标
            revenue_growth = np.random.uniform(-10, 30)  # 营收增长率
            profit_growth = np.random.uniform(-15, 50)   # 利润增长率
            
            return {
                'pe_ratio': pe_ratio,
                'pb_ratio': pb_ratio,
                'roe': roe,
                'roa': roa,
                'gross_margin': gross_margin,
                'net_margin': net_margin,
                'debt_ratio': debt_ratio,
                'current_ratio': current_ratio,
                'revenue_growth': revenue_growth,
                'profit_growth': profit_growth,
                'market_cap': market_cap
            }
            
        except Exception as e:
            print(f"计算财务指标失败: {e}")
            return {}
            
    def analyze_dividend_quality(self, stock_info):
        """分析分红质量"""
        try:
            stock_code = stock_info['code']
            has_dividend = stock_info.get('has_dividend', False)
            dividend_count = stock_info.get('dividend_count', 0)
            current_price = stock_info.get('current_price', 10)
            
            if not has_dividend or dividend_count == 0:
                return {
                    'dividend_yield': 0,
                    'dividend_stability': 0,
                    'dividend_growth': 0,
                    'dividend_score': 10,
                    'dividend_quality': '无分红'
                }
                
            # 模拟分红分析
            avg_dividend = np.random.uniform(0.2, 0.8)  # 平均每股分红
            dividend_yield = (avg_dividend / current_price) * 100
            
            # 分红稳定性评分
            stability_score = min(dividend_count * 15, 90)
            
            # 分红增长性
            dividend_growth = np.random.uniform(-5, 15)
            
            # 综合分红评分
            dividend_score = (
                min(dividend_yield * 10, 40) +     # 分红收益率
                min(stability_score, 40) +         # 稳定性
                max(min(dividend_growth * 2, 20), 0)  # 增长性
            )
            
            if dividend_score >= 80:
                quality = '优秀'
            elif dividend_score >= 60:
                quality = '良好'
            elif dividend_score >= 40:
                quality = '一般'
            else:
                quality = '较差'
                
            return {
                'dividend_yield': dividend_yield,
                'dividend_stability': stability_score,
                'dividend_growth': dividend_growth,
                'dividend_score': dividend_score,
                'dividend_quality': quality
            }
            
        except Exception as e:
            print(f"分析分红质量失败: {e}")
            return {'dividend_score': 0}
            
    def compare_with_industry(self, financial_metrics, industry):
        """与行业对比分析"""
        try:
            benchmark = self.industry_benchmarks.get(industry, self.industry_benchmarks['制造'])
            
            comparisons = {}
            
            # PE比较
            pe_ratio = financial_metrics.get('pe_ratio', 15)
            pe_vs_industry = (benchmark['avg_pe'] - pe_ratio) / benchmark['avg_pe'] * 100
            comparisons['pe_advantage'] = pe_vs_industry
            
            # PB比较
            pb_ratio = financial_metrics.get('pb_ratio', 2.0)
            pb_vs_industry = (benchmark['avg_pb'] - pb_ratio) / benchmark['avg_pb'] * 100
            comparisons['pb_advantage'] = pb_vs_industry
            
            # ROE比较
            roe = financial_metrics.get('roe', 12)
            roe_vs_industry = (roe - benchmark['avg_roe']) / benchmark['avg_roe'] * 100
            comparisons['roe_advantage'] = roe_vs_industry
            
            # 计算行业对比评分
            industry_score = 50  # 基础分
            
            # PE评分（越低越好）
            if pe_vs_industry > 20:
                industry_score += 20
            elif pe_vs_industry > 0:
                industry_score += 10
            elif pe_vs_industry > -20:
                industry_score -= 5
            else:
                industry_score -= 15
                
            # ROE评分（越高越好）
            if roe_vs_industry > 20:
                industry_score += 20
            elif roe_vs_industry > 0:
                industry_score += 10
            elif roe_vs_industry > -20:
                industry_score -= 5
            else:
                industry_score -= 15
                
            industry_score = max(0, min(100, industry_score))
            
            return {
                'industry_score': industry_score,
                'pe_vs_industry': pe_vs_industry,
                'pb_vs_industry': pb_vs_industry,
                'roe_vs_industry': roe_vs_industry,
                'industry_benchmark': benchmark
            }
            
        except Exception as e:
            print(f"行业对比分析失败: {e}")
            return {'industry_score': 50}
            
    def calculate_value_score(self, financial_metrics, dividend_analysis, industry_comparison):
        """计算价值投资评分"""
        try:
            pe_ratio = financial_metrics.get('pe_ratio', 15)
            pb_ratio = financial_metrics.get('pb_ratio', 2.0)
            roe = financial_metrics.get('roe', 12)
            debt_ratio = financial_metrics.get('debt_ratio', 0.5)
            
            value_score = 0
            
            # PE估值评分 (30%)
            if pe_ratio < 10:
                pe_score = 90
            elif pe_ratio < 15:
                pe_score = 70
            elif pe_ratio < 25:
                pe_score = 50
            else:
                pe_score = 20
                
            # PB估值评分 (20%)
            if pb_ratio < 1.5:
                pb_score = 80
            elif pb_ratio < 2.5:
                pb_score = 60
            elif pb_ratio < 3.5:
                pb_score = 40
            else:
                pb_score = 20
                
            # ROE盈利能力评分 (25%)
            if roe > 15:
                roe_score = 90
            elif roe > 10:
                roe_score = 70
            elif roe > 5:
                roe_score = 50
            else:
                roe_score = 20
                
            # 财务健康评分 (15%)
            if debt_ratio < 0.3:
                debt_score = 80
            elif debt_ratio < 0.5:
                debt_score = 60
            elif debt_ratio < 0.7:
                debt_score = 40
            else:
                debt_score = 20
                
            # 分红评分 (10%)
            dividend_score = dividend_analysis.get('dividend_score', 20)
            
            # 综合计算
            value_score = (
                pe_score * 0.30 +
                pb_score * 0.20 +
                roe_score * 0.25 +
                debt_score * 0.15 +
                dividend_score * 0.10
            )
            
            return round(value_score, 1)
            
        except Exception as e:
            print(f"计算价值评分失败: {e}")
            return 50.0
            
    def analyze_single_stock_fundamentals(self, stock_info):
        """分析单只股票基本面"""
        stock_code = stock_info['code']
        stock_name = stock_info['name']
        
        print(f"\n🔍 基本面分析: {stock_code} {stock_name}")
        print("-" * 60)
        
        # 识别行业
        industry = self.identify_industry(stock_code, stock_name)
        print(f"   🏭 行业分类: {industry}")
        
        # 计算财务指标
        financial_metrics = self.calculate_financial_metrics(stock_info)
        print(f"   📊 估值指标: PE {financial_metrics['pe_ratio']:.1f}, PB {financial_metrics['pb_ratio']:.1f}")
        print(f"   💪 盈利能力: ROE {financial_metrics['roe']:.1f}%, 净利率 {financial_metrics['net_margin']:.1f}%")
        print(f"   📈 成长性: 营收增长 {financial_metrics['revenue_growth']:.1f}%, 利润增长 {financial_metrics['profit_growth']:.1f}%")
        
        # 分析分红质量
        dividend_analysis = self.analyze_dividend_quality(stock_info)
        print(f"   💎 分红分析: 股息率 {dividend_analysis['dividend_yield']:.1f}%, 质量 {dividend_analysis['dividend_quality']}")
        
        # 行业对比
        industry_comparison = self.compare_with_industry(financial_metrics, industry)
        print(f"   🏆 行业对比: PE优势 {industry_comparison['pe_vs_industry']:.1f}%, ROE优势 {industry_comparison['roe_vs_industry']:.1f}%")
        
        # 计算价值投资评分
        value_score = self.calculate_value_score(financial_metrics, dividend_analysis, industry_comparison)
        print(f"   💰 价值评分: {value_score}/100")
        
        # 综合基本面评分
        fundamental_score = (
            value_score * 0.6 +
            industry_comparison['industry_score'] * 0.2 +
            dividend_analysis['dividend_score'] * 0.2
        )
        
        print(f"   🏅 基本面评分: {fundamental_score:.1f}/100")
        
        # 返回分析结果
        result = {
            **stock_info,
            'industry': industry,
            'financial_metrics': financial_metrics,
            'dividend_analysis': dividend_analysis,
            'industry_comparison': industry_comparison,
            'value_score': value_score,
            'fundamental_score': round(fundamental_score, 1)
        }
        
        return result
        
    def run_fundamental_analysis(self):
        """运行基本面分析系统"""
        self.print_header("第四步：基本面分析系统 - 深度价值分析")
        
        # 加载技术分析结果
        technical_results = self.load_technical_results()
        if not technical_results:
            print("❌ 无法加载技术分析结果，请先执行第三步")
            return []
            
        print(f"📋 开始对 {len(technical_results)} 只股票进行基本面分析...")
        
        fundamental_results = []
        
        for i, stock_info in enumerate(technical_results, 1):
            print(f"\n[{i:2d}/{len(technical_results)}] 基本面分析进度")
            
            result = self.analyze_single_stock_fundamentals(stock_info)
            if result:
                fundamental_results.append(result)
                
        # 按基本面评分排序
        fundamental_results.sort(key=lambda x: x['fundamental_score'], reverse=True)
        
        # 生成基本面分析报告
        self.generate_fundamental_report(fundamental_results)
        
        return fundamental_results
        
    def generate_fundamental_report(self, fundamental_results):
        """生成基本面分析报告"""
        print(f"\n📊 基本面分析结果统计:")
        print(f"   • 分析股票数量: {len(fundamental_results)}")
        
        if len(fundamental_results) > 0:
            avg_fundamental = sum(r['fundamental_score'] for r in fundamental_results) / len(fundamental_results)
            avg_value = sum(r['value_score'] for r in fundamental_results) / len(fundamental_results)
            print(f"   • 平均基本面评分: {avg_fundamental:.1f}")
            print(f"   • 平均价值评分: {avg_value:.1f}")
            
            # 统计行业分布
            industries = {}
            for result in fundamental_results:
                industry = result['industry']
                industries[industry] = industries.get(industry, 0) + 1
            print(f"   • 行业分布: {', '.join([f'{k}({v})' for k, v in industries.items()])}")
            
            print(f"\n🏆 基本面分析TOP10:")
            print(f"{'排名':<4} {'代码':<8} {'名称':<10} {'行业':<6} {'技术':<6} {'基本面':<8} {'PE':<6} {'ROE':<6} {'分红':<6}")
            print("-" * 78)
            
            for i, result in enumerate(fundamental_results[:10], 1):
                pe = result['financial_metrics']['pe_ratio']
                roe = result['financial_metrics']['roe']
                dividend_quality = result['dividend_analysis']['dividend_quality']
                print(f"{i:<4} {result['code']:<8} {result['name']:<10} "
                      f"{result['industry']:<6} {result['technical_score']:<6.1f} "
                      f"{result['fundamental_score']:<8.1f} {pe:<6.1f} {roe:<6.1f} {dividend_quality:<6}")
                      
            # 推荐价值投资标的
            print(f"\n🎯 价值投资优选 (基本面评分>70):")
            value_stocks = [r for r in fundamental_results if r['fundamental_score'] > 70]
            for i, stock in enumerate(value_stocks[:8], 1):
                pe = stock['financial_metrics']['pe_ratio']
                dividend_yield = stock['dividend_analysis']['dividend_yield']
                print(f"   {i}. {stock['code']} {stock['name']} ({stock['industry']}) - 基本面: {stock['fundamental_score']:.1f} "
                      f"PE: {pe:.1f} 股息率: {dividend_yield:.1f}%")
                
            if not value_stocks:
                print(f"   暂无基本面评分>70的股票，建议降低筛选标准或等待更好时机")
                
        else:
            print(f"   ⚠️ 没有完成基本面分析的股票")
            
    def save_fundamental_results(self, fundamental_results, filename="fundamental_analysis_results.csv"):
        """保存基本面分析结果"""
        if fundamental_results:
            # 简化数据结构用于保存
            save_data = []
            for result in fundamental_results:
                save_record = {
                    'code': result['code'],
                    'name': result['name'],
                    'industry': result['industry'],
                    'current_price': result['current_price'],
                    'market_cap': result['market_cap'],
                    'screening_score': result['screening_score'],
                    'technical_score': result['technical_score'],
                    'fundamental_score': result['fundamental_score'],
                    'value_score': result['value_score'],
                    'pe_ratio': result['financial_metrics']['pe_ratio'],
                    'pb_ratio': result['financial_metrics']['pb_ratio'],
                    'roe': result['financial_metrics']['roe'],
                    'revenue_growth': result['financial_metrics']['revenue_growth'],
                    'profit_growth': result['financial_metrics']['profit_growth'],
                    'dividend_yield': result['dividend_analysis']['dividend_yield'],
                    'dividend_quality': result['dividend_analysis']['dividend_quality'],
                    'has_dividend': result['has_dividend'],
                    'dividend_count': result['dividend_count']
                }
                save_data.append(save_record)
                
            df = pd.DataFrame(save_data)
            df.to_csv(filename, index=False, encoding='utf-8-sig')
            print(f"\n💾 基本面分析结果已保存到 {filename}")
            return filename
        return None

if __name__ == "__main__":
    # 创建基本面分析系统实例
    fundamental_analyzer = FundamentalAnalysisSystem()
    
    # 执行基本面分析
    results = fundamental_analyzer.run_fundamental_analysis()
    
    # 保存结果
    fundamental_analyzer.save_fundamental_results(results)
    
    print(f"\n🎉 第四步：基本面分析系统执行完成！")
    print(f"   • 成功分析了 {len(results)} 只股票的基本面")
    print(f"   • 准备进入第五步：综合评分与排序")
